package com.clay.appointment.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.clay.appointment.common.page.PageInfo;
import com.clay.appointment.dict.client.DictFeignClient;
import com.clay.appointment.entity.hospital.Hospital;
import com.clay.appointment.repository.HospitalRepository;
import com.clay.appointment.service.HospitalService;
import com.clay.appointment.utils.BeanUtils;
import com.clay.appointment.vo.hospital.HospitalQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

import static com.clay.appointment.common.exception.GlobalException.throwOut;

/**
 * @Author : clay
 * @Description:
 * @Date: Create in 21:49 2021/7/30
 * @Modified By:
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;


    @Override
    public void save(Map<String, Object> parameterMap) {

        //把参数Map集合转换成对象Hospital
        String mapString = JSONObject.toJSONString(parameterMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);
        //判断是否存在数据
        String hospitalCode = hospital.getHospitalCode();
        Hospital hospitalExit = hospitalRepository.getHospitalByHospitalCode(hospitalCode);

        //如果不存在，进行添加
        if (hospitalExit == null) {
            hospital.setStatus(true);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setDeleted(false);
            hospitalRepository.save(hospital);
        }
        //如何存在，进行修改
        else {
            BeanUtils.copyProperties(hospital, hospitalExit);
            hospitalRepository.save(hospitalExit);
        }

    }

    @Override
    public Hospital getHospitalByHospitalCode(String hospitalCode) {
        return hospitalRepository.getHospitalByHospitalCode(hospitalCode);
    }

    @Override
    public PageInfo<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //按照创建时间降序排序，即先创建先显示
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                //改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                //改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true);
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        pages.getContent().forEach(this::setHospitalTypeAndProvince);
        return PageInfo.buildPage(pages, Hospital.class);

    }

    @Override
    public void updateStatus(String id, boolean status) {
        //根据id查询医院信息
        Hospital hospital = null;
        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        if (hospitalOptional.isPresent()) {
            hospital = hospitalOptional.get();
        } else {
            throwOut("医院不存在");
        }

        //设置修改的值
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override
    public Hospital getHospitalById(String id) {
        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        if (!StringUtils.isEmpty(hospitalOptional)) {
            if(hospitalOptional.isPresent())
            {
                return this.setHospitalTypeAndProvince(hospitalOptional.get());
            }
        }
        return null;
    }

    @Override
    public String getHospitalNameByHospitalCode(String hospitalCode) {
        Hospital hospital = hospitalRepository.getHospitalByHospitalCode(hospitalCode);
        if (hospital != null) {
            return hospital.getHospitalName();
        }
        return null;
    }

    @Override
    public List<Hospital> findByLikeHospitalName(String hospitalName) {
        List<Hospital> list=hospitalRepository.findHospitalByHospitalNameLike(hospitalName);
        return null;
    }

    @Override
    public Map<String, Object> item(String hospitalCode) {
        Map<String, Object> map = new HashMap<>(16);
        Hospital hospital = this.setHospitalTypeAndProvince(this.getHospitalByHospitalCode(hospitalCode));
        map.put("hospital",hospital);
        map.put("bookingRule",hospital.getBookingRule());
        //没必要返回了
        hospital.setBookingRule(null);
        return map;
    }


    private Hospital setHospitalTypeAndProvince(Hospital hospital) {
        //根据dictCode和value获取医院等级名称
        String hospitalType = dictFeignClient.getName("HospitalType", hospital.getHospitalType());
        //查询省市区
        String province = dictFeignClient.getName(hospital.getProvinceCode());
        String city = dictFeignClient.getName(hospital.getCityCode());
        String District = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("FullAddress", province + city + District);
        hospital.getParam().put("hospitalType", hospitalType);
        return hospital;
    }


}
